package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Queue;
@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Value("${topic.commentTopic}")
    private String commentTopic;
//    回复回复
    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {

        //        判断是否登录  没到登录不能回复回复
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        }
//        现实判断数据有效性，字数不得大于140
        if(dto==null||dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }



//        wenbenguolv(zuoye)


        //        填充返回的对象数据
//        远程调用user获得id和头像
//        保存评论
        ApCommentRepay commentRepay=new ApCommentRepay();
        commentRepay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> userFeignById = userFeign.getById(user.getUserId());
        if(userFeignById.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser=userFeignById.getData();
            commentRepay.setAuthorName(apUser.getName());
        }
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());
        mongoTemplate.save(commentRepay);
        //        评论表的恢复数据+1
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(dto.getCommentId()));

        Update update=new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(query,update, ApComment.class);


//        更新条件
        return ResponseResult.okResult();













    }
//  点赞回复
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
//        可以鲜活地当前用户
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        建一个点赞激励的对象
        ApCommentRepayLike like=new ApCommentRepayLike();
        like.setCommentRepayId(dto.getCommentRepayId());
        like.setAuthorId(user.getUserId());
        like.setOperation(dto.getOperation());
//        查询点赞记录
        Query query=new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));

        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
//        判断是不是空 空保存 不空修改
        if(one==null){
            mongoTemplate.save(like);
//            更新回复表的点赞数量加1
            Query commentQuery=new Query();
            commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update=new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(commentQuery,update,ApCommentRepay.class);
        }else {
            if(one.getOperation()!=dto.getOperation()){
//                判断点赞还是取消
                int num=1;
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                if(dto.getOperation()==1){
                    num= -1;
                }
                Query commentQuery=new Query();
                commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));

                Update update=new Update();
                update.inc("likes");
                mongoTemplate.updateFirst(commentQuery,update,ApCommentRepay.class);

            }
        }


        return ResponseResult.okResult();
    }
// 加载回复
    @Override
    public ResponseResult load(CommentRepayDto dto) {
//        根据wenzhangid 查询评论列表
//        按照 创建之间倒叙
//        分页不小于最小时间
//        meiye默认是10
        if(dto.getSize()==null||dto.getSize()<=0||dto.getSize()>=50){
            dto.setSize(10);
        }
        Query query=new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        PageRequest request = PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createdTime");
       query.with(request);
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);
        User user = AppThreadLocalUtil.get();
//        判断当前用户是否登录
//        在创建一个存储所有点赞记录的一个集合
        List<ApCommentRepayLike> likes=new ArrayList<>();
        if(user!=null){
//            创建一个存储评论id的jihe
            List<String> commentIds=new ArrayList<>();
            for (ApCommentRepay commentRepay:repayList){
                commentIds.add(commentRepay.getCommentId());
            }
            Query likeQuery=new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentRepayId").in(commentIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            mongoTemplate.find(likeQuery,ApCommentRepayLike.class);

        }
        List<String>existCommentIds=new ArrayList<>();
        for(ApCommentRepayLike like:likes){
            existCommentIds.add(like.getCommentRepayId());


        }
//        烦恼vo
        List<ApCommentRepayVo>vos=new ArrayList<>();
        for (ApCommentRepay apCommentRepay:repayList){
            ApCommentRepayVo vo=new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,vo);
            // 默认没有点赞,设置为1
            vo.setOperation(1);
            if (existCommentIds.contains(apCommentRepay.getId())){
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }
}
